<template>
  <div id="processConfigure">
    <div class="processConfigureTree">
      <el-input
        style="width: 90%; margin-left: 5%; margin-bottom: 10px"
        placeholder="输入关键词进行过滤"
        v-model="filterText"
      >
      </el-input>

      <el-tree
        class="filter-tree"
        :data="treeData"
        :props="defaultProps"
        :filter-node-method="filterNode"
        ref="tree"
        :render-content="renderContent"
        show-checkbox
        @check-change="handleCheckChange"
        :default-expanded-keys="expandedKeys"
        :expand-on-click-node="false"
        :default-expand-all="true"
        :highlight-current="true"
        node-key="id"
      >
      </el-tree>
    </div>
    <div class="processConfigureFrom">
      <div style="width: 100%; margin-top: 5px">
        <div class="flex" style="margin-bottom: 10px">
          <el-input
            style="width: 300px; margin-right: 25px"
            v-model="searchKey"
            placeholder="物料名称"
          ></el-input>
          <el-button
            style="width: 80px; height: 34px; margin-top: 3px"
            size="mini"
            type="primary"
            @click="searchKeyBtn('')"
            >查 询</el-button
          >
          <el-button
            style="width: 80px; height: 34px; margin-top: 3px"
            size="mini"
            type="primary"
            @click="reloadBtn('')"
            >重 置</el-button
          >
          <el-button
            style="width: 80px; height: 34px; margin-top: 3px"
            size="mini"
            type="primary"
            @click="editDialog('新增')"
            >新 增</el-button
          >
        </div>
        <el-table
          :data="renderData"
          border
          size="mini"
          style="margin: 0 auto"
          height="800"
          v-loading="loading"
        >
          <el-table-column type="index" label="序号" width="100" align="center" />
          <el-table-column
            prop="typeName"
            label="物料名称"
            align="center"
            min-width="200"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="model"
            label="型号"
            align="center"
            min-width="200"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="unit"
            label="单位"
            align="center"
            min-width="200"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            align="center"
            min-width="200"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            min-width="200"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                style="color: #409eff"
                @click="updateHandler('编辑', scope.row)"
                >编辑</el-button
              >
              <el-button
                type="text"
                style="color: red"
                @click="deleteHandler(1, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row class="footerDiv mt-10">
          <el-pagination
            @size-change="pageSizeChange"
            @current-change="pageNumChange"
            :current-page="pageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev,pager,  next"
            :total="total"
          >
          </el-pagination>
        </el-row>
      </div>
    </div>

    <el-dialog
      :title="editTiele"
      :visible.sync="editDialogStatus"
      width="30%"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="from"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="物料名称" prop="typeId">
          <el-cascader
            :props="props"
            v-model="from.typeId"
            :options="options"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="型号" prop="model">
          <el-input v-model="from.model"></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model="from.unit" placeholder="请选择单位">
            <el-option label="吨" value="吨"></el-option>
            <el-option label="个" value="个"></el-option>
            <el-option label="支" value="支"></el-option>
            <el-option label="套" value="套"></el-option>
            <el-option label="件" value="件"></el-option>
            <el-option label="付" value="付"></el-option>
            <el-option label="批" value="批"></el-option>
            <el-option label="卷" value="卷"></el-option>
            <el-option label="捆" value="捆"></el-option>
            <el-option label="千克" value="千克"></el-option>
            <el-option label="克" value="克"></el-option>
            <el-option label="立方米" value="立方米"></el-option>
            <el-option label="平方米" value="平方米"></el-option>
            <el-option label="米" value="米"></el-option>
            <el-option label="延米" value="延米"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="from.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogStatus = false">取 消</el-button>
        <el-button type="primary" @click="editSaveHandler('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="editTiele2"
      :visible.sync="editDialogStatus2"
      width="30%"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="typeFrom"
        :rules="rules"
        ref="ruleForm2"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="物料名称" prop="name2">
          <el-input v-model="typeFrom.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogStatus2 = false">取 消</el-button>
        <el-button type="primary" @click="editSaveHandler2('ruleForm2')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMaterial,
  getByIdMaterial,
  getMaterialPage,
  addMaterialInfo,
  deleteMaterialInfo,
  updateMaterialInfo,
  addMaterial,
  updateMaterial,
  deleteMaterial,
} from "/src/http/backstageManage/materialDispatch/materialTypeMg.js";

export default {
  data() {
    return {
      filterText: "",
      searchKey: "",
      renderData: [],
      treeData: [],
      props: { value: "id", label: "name" },
      defaultProps: {
        children: "children",
        label: "name",
      },
      // 分页
      pageNum: 1,
      pageSize: 20,
      total: 0,
      //
      loading: true,
      options: [],
      select: "",
      editDialogStatus: false,
      editDialogStatus2: false,
      editTiele: "",
      editTiele2: "",
      from: {},
      typeFrom: {},
      rules: {
        wlgl: [{ required: true, message: "物料名称不能为空", trigger: "blur" }],
        typeId: [{ required: true, message: "请选择物料名称", trigger: "blur" }],
        name: [{ required: true, message: "请输入物料名称", trigger: "blur" }],

        model: [{ required: true, message: "请输入规格型号", trigger: "blur" }],
        unit: [{ required: true, message: "请选择单位", trigger: "blur" }],
      },
      PidArr: [],
      allOptions: [],
      timeFun: null,
      expandedKeys: [],
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted() {
    this.getListApi();
    this.getRenderData();
  },

  methods: {
    //检索
    filterNode(value, data) {
      console.log(value, data);
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleCheckChange(data, checked, indeterminate) {
      let arr = [];
      this.$refs.tree.getCheckedNodes().forEach((item) => {
        if (!item.children || item.children === null) {
          arr.push(item.id);
        }
      });
      this.PidArr = arr.join(",");
      clearTimeout(this.timeFun);
      this.loading = true;
      this.timeFun = setTimeout(() => {
        this.pageNum = 1;
        this.getRenderData();
      }, 1000);
    },
    // 自定义树形控件内容
    renderContent(h, { node, data, store }) {
      if (data.children) {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
            <span>
              <el-button
                style="color:#409EFF"
                size="mini"
                type="text"
                on-click={() => this.updateType(data)}
              >
                编辑
              </el-button>
              <el-button
                style="color:#67C23A"
                size="mini"
                type="text"
                on-click={() => this.addType(data)}
              >
                添加
              </el-button>
              <span style="width:26px;height:5px;    display: inline-block;    margin-left: 10px;"></span>
            </span>
          </span>
        );
      } else {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
            <span>
              <el-button
                style="color:#409EFF"
                size="mini"
                type="text"
                on-click={() => this.updateType(data)}
              >
                编辑
              </el-button>
              <el-button
                style="color:#67C23A"
                size="mini"
                type="text"
                on-click={() => this.addType(data)}
              >
                添加
              </el-button>
              <el-button
                style="color:#F56C6C"
                size="mini"
                type="text"
                on-click={() => this.deleteHandler(2, data)}
              >
                删除
              </el-button>
            </span>
          </span>
        );
      }
    },
    searchKeyBtn() {
      this.pageNum = 1;
      this.getRenderData();
    },
    reloadBtn() {
      this.pageNum = 1;
      this.searchKey = "";
      this.getRenderData();
    },
    pageNumChange(v) {
      this.pageNum = v;
      this.getRenderData();
    },
    pageSizeChange(v) {
      this.pageSize = v;
      this.pageNum = 1;
      this.getRenderData();
    },
    updateType(data) {
      this.editTiele2 = "编辑";
      this.editDialogStatus2 = true;
      console.log(data);
      this.typeFrom = {
        name: data.name,
        pid: data.pid,
        id: data.id,
      };
    },
    addType(data) {
      this.editTiele2 = "新增子节点";
      this.editDialogStatus2 = true;
      console.log(data);
      this.typeFrom = {
        pid: data.id,
      };
    },
    // 新增
    editSaveHandler(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.editTiele == "新增") {
            let params = JSON.parse(JSON.stringify(this.from));
            params.typeId = params.typeId[params.typeId.length - 1];
            console.log(params);
            addMaterialInfo(params).then((res) => {
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: "新增成功!",
                });
                this.editDialogStatus = false;

                this.getRenderData();
              } else {
                this.$message.error(res.message);
              }
            });
          } else if (this.editTiele == "编辑") {
            let params = JSON.parse(JSON.stringify(this.from));
            console.log(typeof params.typeId);
            if (typeof params.typeId === "number") {
            } else {
              params.typeId = params.typeId[params.typeId.length - 1];
            }

            console.log(params);
            updateMaterialInfo(params).then((res) => {
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: "编辑成功!",
                });
                this.editDialogStatus = false;

                this.getRenderData();
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    editSaveHandler2(formName) {
      if (!this.typeFrom.name) {
        this.$message.error("物料名称名称不能为空");
        return;
      }
      if (this.editTiele2 === "编辑") {
        let params = JSON.parse(JSON.stringify(this.typeFrom));
        updateMaterial(params).then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "编辑成功!",
            });
            this.editDialogStatus2 = false;
            this.getListApi();
          } else {
            this.$message.error(res.message);
          }
        });
      } else if (this.editTiele2 === "新增子节点") {
        let params = JSON.parse(JSON.stringify(this.typeFrom));
        addMaterial(params).then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "编辑成功!",
            });
            this.editDialogStatus2 = false;
            this.getListApi();
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },

    /**接口 */
    // 查询项目列表
    getListApi() {
      getMaterial().then((res) => {
        if (res.code == 200) {
          this.treeData = [
            {
              id: 0,
              children: res.data,
              name: "物资类型",
            },
          ];

          this.options = res.data;
          this.arrForEach(res.data);
          res.data.forEach((item) => {
            this.expandedKeys.push(item.id + "");
            if (item.children) {
              item.children.forEach((i) => {
                this.expandedKeys.push(i.id + "");
                if (i.children) {
                  i.children.forEach((e) => {
                    this.expandedKeys.push(e.id + "");
                  });
                }
              });
            }
          });
          console.log(this.expandedKeys);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    getRenderData() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        searchKey: this.searchKey,
      };
      params.typeIdList = this.PidArr;
      getMaterialPage(params).then((res) => {
        if (res.code === 200) {
          this.renderData = res.data.records;
          this.total = res.data.total;
          this.loading = false;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    arrForEach(arr) {
      arr.forEach((item) => {
        this.allOptions.push(item);
        if (item.children) {
          this.arrForEach(item.children);
        }
      });
    },

    //删除
    deleteHandler(type, v) {
      console.log("delete::: ", v);
      this.$confirm("此操作将删除该配置项?", "提示", {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          switch (type) {
            case 1:
              deleteMaterialInfo({ idList: [v.id] }).then((res) => {
                if (res.code === 200) {
                  this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                  this.getRenderData();
                } else {
                  this.$message.error(res.message);
                }
              });
              break;
            case 2:
              deleteMaterial({ idList: [v.id] }).then((res) => {
                if (res.code === 200) {
                  this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                  this.getListApi();
                } else {
                  this.$message.error(res.message);
                }
              });
              break;

            default:
              break;
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    editDialog(name) {
      this.editDialogStatus = true;
      this.editTiele = name;
      this.from = { name: "" };
    },
    updateHandler(name, data) {
      console.log(data);
      this.from = {
        typeId: data.typeId,
        model: data.model,
        name: data.typeName,
        unit: data.unit,
        remark: data.remark,
        id: data.id,
      };
      this.editDialogStatus = true;
      this.editTiele = name;
      // this.from = JSON.parse(JSON.stringify(data));
    },
  },
};
</script>

<style lang="less" scoped>
#processConfigure {
  display: flex;
  justify-content: space-between;

  height: 100%;
  .processConfigureTree {
    padding-top: 1rem;
    width: 20%;
    height: 100%;
    background: #fff;
    overflow: auto;
  }
  .processConfigureFrom {
    width: 78%;
    height: 100%;
    background: #fff;
    padding: 1rem 2rem;
    h1 {
      font-size: 20px;
    }
  }

  :deep(.custom-tree-node) {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .footerDiv {
    padding: 10px;
    border-radius: 5px;
    background-color: #fff;
    box-shadow: 1px 1px 10px 1px rgba(0, 0, 0, 0.1);
  }
}
</style>
